//
//  Enemy.swift
//  ShapeSurvival
//
//  Created by Jerry H on 1/8/15.
//  Copyright (c) 2015 HeylmunProgramming. All rights reserved.
//

import Foundation; import SpriteKit; import Darwin

class Enemy: SKSpriteNode {
    var type: Int = 0;
    var health: Int = 1;
    var movespeed: CGFloat = 1.0;
    var facing:Bool = false;
    var chase  = true;
    var canBeShot = true;
    var spawnTime: CGFloat = 0.00
    var emomentum: CGFloat = 0.3
    var lifeTime: CGFloat = 0.00
    var value: Int = 1
    var rotatesPerSecond: CGFloat = 1 // Degrees
    var lastRotate: CGFloat = 0.00
    
    func setEnemy(Xpos: CGFloat, Ypos: CGFloat, startingAngle: CGFloat){
        self.position.x = Xpos;
        self.position.y = Ypos;
        self.zPosition = 0.5
        self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        self.setRotation(startingAngle)
        self.setStats()
        
        eManager.currentEnemies.append(self)
        playScene.addChild(self);
    }
    
    func setStats(){
        //To Be overwritten by sub classes.
    }
    
    func setRotation(rotate: CGFloat){
        var temp = rotate  //- 180
        while(temp > 360){
            temp = temp - 360
        }
        temp = (temp / 57.2957795)
        self.zRotation = temp
    }
    
    func getRotation() -> CGFloat{
        var n = (zRotation * 57.2957795)
        while( n > 360 ) {
            n = n - 360
        }
        while( n < -360 ) {
            n = n + 360
        }
        if( n < 0){
            n = 360 + n
        }
        return n
    }
    
    func distanceToPlayer() -> CGFloat {
        var x = (player.position.x - self.position.x)
        var y = (player.position.y - self.position.y)
        return sqrt((x * x) + (y * y))
    }
    
    func angleToPlayer(degrees: Bool )-> CGFloat {
        var n = (atan(((player.position.x - self.position.x) / (player.position.y - self.position.y))) * 57.2957795)
        n = n + getRotation()
        
        if(player.position.y < self.position.y){
            n = n + 180
            //n = ((180 - n) - 360 )//* -1)
        }
        if( n > 180){
            n = n - 360
        }
        if(degrees == true){
            return n
        }
        else{
            n = n / 57.2957795
            return n
        }
    }
    
    func facePlayer() -> SKAction{
        let angTo = angleToPlayer(true)
        let timelapse = ((runTime - lastRotate)) * rotatesPerSecond
        let invLapse = timelapse * -1
        var turning = (-1 * angleToPlayer(false))
        lastRotate = runTime
        if(turning > timelapse){
            return(SKAction.rotateByAngle(timelapse, duration: 0.0))
        }
        else if(turning < invLapse){
            return(SKAction.rotateByAngle(invLapse, duration: 0.0))
        }
        else {
            return(SKAction.rotateByAngle(turning, duration: 0.0))
        }
    }
    
    func setSpeedBoost() -> CGFloat {
        return movespeed / 50
    }
    
    func moveByFacing(length: CGFloat) -> SKAction {
        var speedBoost = setSpeedBoost()
        let y =  -1 * (sin(zRotation - (CGFloat(M_PI) / 2))) * speedBoost
        
        let x =  -1 * (cos(zRotation - (CGFloat(M_PI) / 2))) * speedBoost
        
        let n: CGVector = CGVector(dx: x, dy: y)
        
        return SKAction.moveBy(n, duration: NSTimeInterval(length))
    }
    
    func moveWithoutFacing() -> SKAction {
        var xdistance = self.position.x - player.position.x
        var ydistance = self.position.y - player.position.y
        
        var ehyp = sqrt((xdistance * xdistance) + (ydistance * ydistance))
        var edis = ehyp
        let ecos = (xdistance / ehyp)
        let esin = (ydistance / ehyp)
        
        var enewx = self.position.x - (ecos * 50)
        var enewy = self.position.y - (esin * 50)
        var exspeed = (0-ecos)
        var eyspeed = (0-esin)
        
        var edegrees = CGVector(dx: (exspeed * (movespeed / 25)), dy: (eyspeed * (movespeed / 25)))
        let emove = SKAction.moveBy(edegrees, duration: 0.5)
        return emove
    }
    
    func moveSelf(PlayerX: CGFloat, PlayerY: CGFloat ) {
        
        checkChanges()
        
        if(self.facing == true){
            if(self.chase == true){
                let face = facePlayer()
                let move = moveByFacing(emomentum)
                self.runAction(SKAction.group([move, face]))
            }
            //self.runAction(move)
        }
        else if(self.chase == true){
            self.runAction(moveWithoutFacing())
        }
        else{
            // Go straight
            self.runAction(moveByFacing(emomentum))
        }
        
        //label1.text = "\(self.angleToPlayer(true)), \(self.getRotation()), \(self.angleToPlayer(false))"
        
        
    }
    
    func createExplosion(type: Int, elength: CGFloat, esize: CGFloat, epoint: CGPoint){
        let temp: Explosion = Explosion(imageNamed: "Explosion");
        temp.setUp(type, length: elength, size: esize, point: epoint)
    }
    
    
    func checkChanges(){
        lifeTime = CGFloat(CGFloat(runTime) - CGFloat(spawnTime))
    }
    
    func die(){
        self.runAction(SKAction.scaleTo(0.0, duration: 0.1), completion: {
            let tempE = find(eManager.currentEnemies, self)
            var setE = -1
            if(tempE? != nil){
                setE = Int(tempE!)
                if(setE != -1){
                    eManager.currentEnemies.removeAtIndex(setE)
                    self.removeFromParent()
                    score = score + (self.value)
                }
            }
            
        })
    }
    
    func takeDamage() {
        self.health = self.health - 1
        if(self.health == 0){
            //score = score + (value)
            self.die()
        }
    }
}
